package com.ccg.plat.presentation.common.base.viewmodel

import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.ccg.plat.data.remote.api.NetService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import retrofit2.Retrofit
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.coroutines.cancellation.CancellationException

/**
 * @author : C4_雍和
 * 描述 :
 * 主要功能 :
 * 维护人员 : C4_雍和
 * date : 2025/8/9 7:56
 */
open class BaseViewModelC(application: Application) : AndroidViewModel(application), LifecycleObserver {
    val retrofit = Retrofit.Builder().baseUrl("https://your.api.url/").build().create(NetService::class.java)

    /**
     * 如果联网请求出现异常,这个数据中就会有异常信息
     */
    val mException = MutableLiveData<Exception>()
    fun launch(context: CoroutineContext = EmptyCoroutineContext, tryBlock: suspend CoroutineScope.() -> Unit) {
        viewModelScope.launch(context = context) {
            tryCatch(tryBlock, {
                Log.e("error", "报错信息:  $it")
            }, {}, true)
        }
    }

    private suspend fun tryCatch(tryBlock: suspend CoroutineScope.() -> Unit, catchBlock: suspend CoroutineScope.(Throwable) -> Unit, finallyBlock: suspend CoroutineScope.() -> Unit, handleCancellationExceptionManually: Boolean = false) {
        coroutineScope {
            try {
                tryBlock()
            } catch (e: Exception) {
                if (e !is CancellationException || handleCancellationExceptionManually) {
                    mException.postValue(e)
                    catchBlock(e)
                } else {
                    throw e
                }
            } finally {
                finallyBlock()
            }
        }
    }
}